package edu.stu.mall.compent

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Point
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import edu.stu.mall.R

class ScrollBar @JvmOverloads constructor(
    //通过 @JvmOverloads 注解提供了多个重载的构造函数，以支持不同的参数组合。
    context: Context,
    attr: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attr, defStyleAttr) {

    // 定义滚动条宽度和高度
    private val RECT_WIDTH = 30f
    private val RECT_HEIGHT = 10f
    // 定义滚动条圆角半径
    private val CORNER_RADIUS = 10f
    // 定义滚动条与边界的间距
    private val MARGIN = 5f

    // 当前滚动条的位置
    private lateinit var currentPoint: Point

    // 画笔，用于绘制滚动条
    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = ContextCompat.getColor(context, R.color.colorPrimary)
    }

    // 标记是否已经初始化
    private var isInit = false

    // 获取滚动条是否已经初始化
    fun getInitialState() = isInit

    // 重写 onDraw 方法，绘制滚动条
    @SuppressLint("Recycle", "DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 获取视图中心的 y 坐标
        val centerY = height / 2

        // 初始化 currentPoint 为视图左边中心位置
        if (!::currentPoint.isInitialized) {
            currentPoint = Point((MARGIN + RECT_WIDTH / 2).toInt(), centerY)
        }

        // 绘制圆角矩形作为滚动条
        val left = currentPoint.x - RECT_WIDTH / 2
        val top = currentPoint.y - RECT_HEIGHT / 2
        val right = currentPoint.x + RECT_WIDTH / 2
        val bottom = currentPoint.y + RECT_HEIGHT / 2
        val rect = RectF(left, top, right, bottom)
        canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, mPaint)

        // 标记为已初始化
        isInit = true
    }

    // 动画到指定的百分比位置
    fun animateTo(percent: Float) {
        // 根据百分比计算目标位置的 x 坐标
        var targetX = (percent * width).toInt()
        val halfRectWidth = (RECT_WIDTH / 2).toInt()

        // 确保目标位置不会超出视图边界
        targetX = when {
            targetX < halfRectWidth + MARGIN.toInt() -> (halfRectWidth + MARGIN.toInt())
            targetX > width - halfRectWidth - MARGIN.toInt() -> (width - halfRectWidth - MARGIN.toInt())
            else -> targetX
        }

        // 更新当前滚动条的位置
        currentPoint = Point(targetX, currentPoint.y)
        // 重新绘制视图
        invalidate()
    }
}
